package com.qqtech.qquan.v1_4.contoller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.enums.CircleAuditStatusEnum;
import com.qqtech.qquan.circle.enums.CircleBaseStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleBaseTypeDictEnum;
import com.qqtech.qquan.circle.enums.CircleFuncTypeDictEnum;
import com.qqtech.qquan.circle.enums.CircleOpenLevelDictEnum;
import com.qqtech.qquan.circle.model.CircleBase;
import com.qqtech.qquan.circle.model.CircleBaseQuery;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleInfoQuery;
import com.qqtech.qquan.circle.model.CircleInfoVo;
import com.qqtech.qquan.circle.model.CircleMemberQuery;
import com.qqtech.qquan.circle.service.CircleApplyService;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleCategoryService;
import com.qqtech.qquan.circle.service.CircleInfoService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.circle.service.CircleSignService;
import com.qqtech.qquan.circle.service.CircleSysDictService;
import com.qqtech.qquan.circle.service.CircleTopicService;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.im.service.ImGroupService;
import com.qqtech.qquan.sys.model.SysArea;
import com.qqtech.qquan.sys.service.SysAreaService;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/v1.4/index")
public class IndexPageController extends BaseWebController<CircleBase, CircleBaseQuery> {
	@Resource
	private SysAreaService sysAreaService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private CircleSignService circleSignService;
	@Resource
	private CircleCategoryService circleCategoryService;
	@Resource
	private CommunityBaseService communityBaseService;
	@Resource
	private CircleBaseService circleBaseService;
	@Resource
	private CircleInfoService circleInfoService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private CircleSysDictService circleSysDictService;
	@Resource
	private CommunityJoinService communityJoinService;
	@Resource
	private ImGroupService imGroupService;
	@Resource
	private CircleTopicService circleTopicService;
	@Resource
    private CircleApplyService circleApplyService;
	
	@Override
	protected BaseService<CircleBase> getBaseService() {
		return circleBaseService;
	}

	/**
	 * 新版加入圈子-主要判断当前用户所定位的城市是否和圈子的城市id一致，不一致则不允许加入
	 * @param circleMember
	 * @return
	 * @throws BizzException 
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/circle/join")
	@ResponseBody
	public Result joinCircle(@RequestBody CircleMemberQuery circleMember) throws BizzException{
		Result result = new Result();
		if(circleMember==null){
			result.addErr("新增成员信息为空！");
			return result;
		}
		Integer curUserId = super.getUserId();//当前用户id
		Integer circleId =circleMember.getCircleId();
		CircleBaseVo circleVo = circleBaseService.getById(circleId);
		if(circleVo==null){
			result.addErr("圈子数据有误");
			return result;
		}
		if (circleVo.isPrivate()) {//私密圈子
			result.addErr("不能直接加入私有圈子！");
			return result;
		}else {
			Integer cityId = circleMember.getCityId();
			if (cityId!=null&&circleVo.getCityId()!=null&&cityId.intValue()!=circleVo.getCityId().intValue()) {
				result.addErr("您的定位城市和圈子所在城市不一致");
				return result;
			}
			if(circleVo.getOpenLevel()== CircleOpenLevelDictEnum.HALF_OPEN.getCode()){
				//半开放圈子，提交加入申请
				int appId = circleApplyService.apply2JoinCircle(curUserId, circleId);
				if(appId>0){
					result.put("myMsg", "您已成功提交了加入申请");
				}
			}else if(circleVo.getOpenLevel()== CircleOpenLevelDictEnum.FULL_OPEN.getCode()){
				//全开放圈子，直接加入
				circleMemberService.handleJoinCircle(curUserId, circleId, true);//直接加入
			}
		}
		return result;
	}
	
	/**
	 * 新版创建圈子-地区只有全国和城市两个级别，不关联社区信息
	 * @param circle
	 * @return
	 * @throws BizzException
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/circle/create")
	@ResponseBody
	public Result circleCreate(@RequestBody CircleBase circle) throws BizzException {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		if (circle.getCityId() == 0) {
			circle.setCityId(null);
		}
		circle.setCreatorId(curUserId);
		circle.setType(CircleBaseTypeDictEnum.POPULAR.getCode());// 民间圈子
		if (validateCircle(circle, result, true)) {
			circleBaseService.addCircle(circle);
		}
		return result;
	}
	
	/**
	 * 我的圈子列表
	 *
	 * @param auth
	 * @return
	 */
	@RequestMapping(value = "/circle/new")
	@ResponseBody
	public Result newCircle() {
		Result result = new Result();
		CircleBaseQuery circleQuery = new CircleBaseQuery();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		String cityName = "全国";
		Pageable pageKit = new PageKit(circleQuery.getPage(),10, new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : page) {
			Integer cityId = circleBaseVo.getCityId();
			if(cityId!=null&&cityId.intValue()>0) {
				SysArea area = sysAreaService.getById(cityId);
				if(area!=null) {
					cityName = area.getName();
				}
			}
			circleBaseVo.setCityName(cityName);
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("page", page);
		return result;
	}
	
	/**
	 * 我的圈子列表（包括我创建的圈子和加入的圈子）
	 *
	 * @param auth
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/circle/my")
	@ResponseBody
	public Result myCircles() {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		CircleMemberQuery query = new CircleMemberQuery();
		query.setMemberId(curUserId);
		List<CircleBaseVo> circleList = circleBaseService.queryMyCircles(query);
		result.put("circleList", circleList);
		return result;
	}
	
	/**
	 * 综合
	 * @param circleQuery
	 * @return
	 */
	@RequestMapping(value = "/circle/list/default")
	@ResponseBody
	public Result listDefault() {
		Result result = new Result();
		CircleBaseQuery circleQuery = new CircleBaseQuery();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		String cityName = "全国";
		circleQuery.setIsRecommend(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : page) {
			Integer cityId = circleBaseVo.getCityId();
			if(cityId!=null&&cityId.intValue()>0) {
				SysArea area = sysAreaService.getById(cityId);
				if(area!=null) {
					cityName = area.getName();
				}
			}
			circleBaseVo.setCityName(cityName);
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("page", page);
		return result;
	}
	
	/**
	 * 根据地区搜索圈子
	 * 
	 * @param circleQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/circle/list/zone")
	@ResponseBody
	public Result listZone(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		String cityName = "全国";
		Integer cityId = circleQuery.getCityId();
		if(cityId!=null&&cityId.intValue()>0) {
			SysArea area = sysAreaService.getById(cityId);
			if(area!=null) {
				cityName = area.getName();
			}
		}else {
			cityId = null;
			circleQuery.setCityId(cityId);
		}
		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : page) {
			if(cityId==null) {
				SysArea area = sysAreaService.getById(circleBaseVo.getCityId());
				if(area!=null) {
					circleBaseVo.setCityName(area.getName());
				}else {
					circleBaseVo.setCityName("全国");
				}
			}else {
				circleBaseVo.setCityName(cityName);
			}
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("page", page);
		return result;
	}
	
	
	/**
	 * 根据标签搜索圈子
	 * 
	 * @param circleQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/circle/list/tagName")
	@ResponseBody
	public Result listTagName(@RequestBody CircleBaseQuery circleQuery) {
		Result result = new Result();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		Pageable pageKit = new PageKit(circleQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> page = circleBaseService.queryPageList(circleQuery, pageKit);
		CircleInfoVo circleInfoVoTemp = null;
		String cityName = "全国";
		for (CircleBaseVo circleBaseVo : page) {
			Integer cityId = circleBaseVo.getCityId();
			if(cityId!=null&&cityId.intValue()>0) {
				SysArea area = sysAreaService.getById(cityId);
				if(area!=null) {
					cityName = area.getName();
				}
			}
			circleBaseVo.setCityName(cityName);
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		result.put("page", page);
		return result;
	}
	
	/**
	 * 根据成员人数升降序圈子
	 * 
	 * @param circleQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/circle/list/member")
	@ResponseBody
	public Result listMember(@RequestBody CircleInfoQuery circleQuery) {
		Result result = new Result();
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		// 包含的开放状态【公开：任意加入;半开放:申请加入】
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleQuery.setIncludeOpenLevels(includeOpenLevelList);
		// 包含的功能类型【全功能、话题功能】-排除只有群聊功能的圈子
		List<Integer> includeFunctypeList = Lists.newArrayList();
		includeFunctypeList.add(CircleFuncTypeDictEnum.ALL.getCode());
		includeFunctypeList.add(CircleFuncTypeDictEnum.TOPICONLY.getCode());
		circleQuery.setIncludeFuncTypes(includeFunctypeList);

		PageOrder pageOrder = new PageOrder(Direction.DESC, "t.memberCount");
		String member = circleQuery.getMember();
		if(StringUtil.isNotBlank(member)&&"asc".equals(member)) {
			pageOrder = new PageOrder(Direction.ASC, "t.memberCount");
		}
		Pageable pageKit = new PageKit(circleQuery.getPage(), pageOrder);
		Page<CircleInfoVo> page = circleInfoService.queryListBaseInfo(circleQuery, pageKit);
		String cityName = "全国";
		for (CircleInfoVo circleBaseVo : page) {
			//System.out.println("circleBaseVo-FullLogo===="+circleBaseVo.getFullLogo());
			Integer cityId = circleBaseVo.getCityId();
			if(cityId!=null&&cityId.intValue()>0) {
				SysArea area = sysAreaService.getById(cityId);
				if(area!=null) {
					cityName = area.getName();
				}
			}
			circleBaseVo.setCityName(cityName);
		}
		result.put("page", page);
		return result;
	}
	
	/**
	 * @param circle
	 * @param ret
	 * @param addMethod
	 *            是否是圈子添加操作
	 * @return
	 */
	private boolean validateCircle(CircleBase circle, Result ret, boolean addMethod) {
		if (addMethod == false && circle.getId() == null) {
			ret.addErr("圈子id为空！");
		}
		if (addMethod == true && circle.getType() == null) {
			ret.addErr("请选择圈子类型");
		}
		if (addMethod && StringUtils.isBlank(circle.getName())) {
			ret.addErr("请填写圈子名称");
		}
		if (StringUtils.isBlank(circle.getRemark())) {
			ret.addErr("请填写圈子说明");
		}
		if (StringUtils.isBlank(circle.getLogo())) {
			ret.addErr("请上传圈子图片");
		}
		return ret.checkForm();
	}
}
